import redis
import json
import time
import copy
import numpy
from loguru import logger
from typing import List

class RedisClient:
    def __init__(self, host, port, db, max_connections, password=None):
        self.pool = redis.ConnectionPool(host=host, port=port, db=db, max_connections=max_connections)
        self.client = redis.Redis(host=host, port=port, db=db, password="Mars_nginx_chat_llm")

    def get(self, key):
        try:
            return self.client.get(key)
        except redis.RedisError as e:
            # 处理Redis错误
            logger.error(f"Redis get error: {e}")
            return None

    def set(self, key, value):
        try:
            self.client.set(key, value)
        except redis.RedisError as e:
            # 处理Redis错误
            logger.error(f"Redis set error: {e}")

    def delete(self, key):
        try:
            self.client.delete(key)
        except redis.RedisError as e:
            # 处理Redis错误
            logger.error(f"Redis delete error: {e}")

class ChatHistory:
    def __init__(self, uid, redis_client, history_len):
        self.uid = uid
        self.redis_client = redis_client
        self.history_len = history_len

        # 在初始化时获取历史记录
        self.history_json = self.redis_client.get(self.uid)
        if self.history_json:
            self.old_history = json.loads(self.history_json)
        else:
            self.old_history = []

    def get_history(self):
        if self.history_json:
            try:
                history = json.loads(self.history_json)
                # 进一步处理 history...
                self.old_history = copy.deepcopy(history)
                try:
                    not_null = [i[:2] for i in self.old_history[-self.history_len:] if i[1].get("content") != '']
                    if not_null:
                        history = numpy.concatenate(
                            not_null).tolist()
                    else:
                        history = []
                except Exception as e:
                    logger.error(f"An error occurred: {e}")
                    self.clear_history()
                    history = []
                return history
            except json.JSONDecodeError:
                self.clear_history()
                return []
            except (IndexError, TypeError, ValueError, numpy.AxisError) as e:
                logger.error(f"An error occurred while processing history: {e}")
                self.clear_history()
                return []
        else:
            return []

    def add_to_history(self, message: List):
        # 添加对话消息到历史记录
        if self.history_json:
            history = self.old_history
        else:
            history = []
        history.append(message)
        self.history_json = json.dumps(history)  # 更新 self.history_json
        self.redis_client.set(self.uid, self.history_json)

    def clear_history(self):
        self.redis_client.delete(self.uid)
        self.history_json = None  # 清空 self.history_json